package com.ruoyi.core.lock;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
@Data
@ConfigurationProperties(prefix = "spring.redis")
public class RedissonUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedissonUtil.class);

    private String host;

    private Integer port;

    private String password;


    private static RedissonClient redissonClient;

    static RedissonClient getRedissonClient() {
        return redissonClient;
    }

    private RedissonUtil() {
    }

    public static RedissonUtil getInstance() {
        return InstanceHolder.instance;
    }

    private static class InstanceHolder {
        private static final RedissonUtil instance = new RedissonUtil();
    }

    @PostConstruct
    private void init() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port);
        if (StringUtils.isNotBlank(password)) {
            config.useSingleServer().setPassword(password);
        }
        redissonClient = Redisson.create(config);
    }

    public void set(String key, Object value, Integer expire){
        RBucket<Object> rbucket = redissonClient.getBucket(key);
        if(expire == null){
            rbucket.set(value);
        }else{
            rbucket.set(value,expire, TimeUnit.SECONDS);
        }
    }

    public Long ttl(String key){
        return redissonClient.getBucket(key).remainTimeToLive();
    }
}
